﻿using Minecraft.CacheRedis;
using Minecraft.Config;
using Minecraft.Config.Csv.CsvCls;
using Minecraft.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Minecraft.BLL.mysql
{
	public class BlueprintBLL : BaseBLL
	{
		private static RedisCacheHelper redisCacheHelper = new RedisCacheHelper();
		private static RedisKey redisKeyEnum = RedisKey.Blueprint;
		public static BlueprintModel GetSingleOrDefault(int playerId, out bool fromCache)
		{
			fromCache = false;
			string redisKey = RedisKeyHelper.GetRedisKeyName(redisKeyEnum, playerId.ToString());
			var cacheModel = redisCacheHelper.StringGet<BlueprintModel>(redisKey);
			if (cacheModel != null)
			{
				fromCache = true;
				return cacheModel;
			}
			else
			{
				var model = new BlueprintModel();
				model = GetSingleOrDefault(model, new KeyValuePair<string, int>(nameof(model.PlayerId), playerId));
				if (model == null)
				{
					model = new BlueprintModel
					{
						PlayerId = playerId,
						//BlueprintIdAndStudyStr = string.Join("#", CsvConfig.blueprintList.OrderBy(m => m.Place_Convert).Select(m => new { blueprintId = m.Id, isOneStr = "0" })
						//  .ToList().ConvertAll(m => string.Join("|", m.blueprintId, m.isOneStr)).ToArray())
						BlueprintIdAndStudyStr = string.Join("#", CsvConfig.GetblueprintDict().Select(m => m.Value).OrderBy(m => m.Place_Convert).Select(m => new { blueprintId = m.Id, isOneStr = "0" })
						  .ToList().ConvertAll(m => string.Join("|", m.blueprintId, m.isOneStr)).ToArray())
					};
					BatchInsert(new List<BlueprintModel> { model });
				}
				redisCacheHelper.StringSet(redisKey, model, CommonConfig.DefRedisExpiry);
				return model;
			}
		}

		public static bool Update(BlueprintModel model, bool isCacheAfterDbOpt)
		{
			string redisKey = RedisKeyHelper.GetRedisKeyName(redisKeyEnum, model.PlayerId.ToString());
			redisCacheHelper.StringSet(redisKey, model, CommonConfig.DefRedisExpiry);
			if (isCacheAfterDbOpt)
			{
				return Update(model, nameof(model.PlayerId));
			}
			return true;
		}
	}
}
